/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package packageController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import packageModel.Product;
import packageModel.Basket;
import packageBusiness.BricoWebUserBusiness;
import packageException.*;
import packageModel.Category;
import java.text.DecimalFormat; 
/**
 *
 * @author laurent
 */
public class CatalogController extends HttpServlet 
{
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    {
        response.setContentType("text/html;charset=UTF-8");
        HttpSession session = request.getSession();
        RequestDispatcher rd = null;
        
        BricoWebUserBusiness businessLayer = new BricoWebUserBusiness();
        ArrayList<Category> allCategories;
        ArrayList<Product> productsCategory;
        Product productSelected;
        Integer idCategory, idProduct, quantityProd;
        Basket basket;
        
          
        if(request.getParameter("selectedCategory") != null)
        {
            idCategory = Integer.parseInt(request.getParameter("selectedCategory"));
            session.setAttribute("defaultCategory", idCategory);
        }
        else if((Integer)session.getAttribute("defaultCategory") != null)
            idCategory = (Integer)session.getAttribute("defaultCategory");      
        else
            idCategory = 1;

        
        if(request.getParameter("selectedProduct") != null)
        {
            idProduct = Integer.parseInt(request.getParameter("selectedProduct"));
            session.setAttribute("defaultProduct", idProduct);
            session.setAttribute("defaultQuantity", 1);
        }
        else if((Integer)session.getAttribute("defaultProduct") != null)
            idProduct = (Integer)session.getAttribute("defaultProduct");
        else
            idProduct = null;
        
        
        if(request.getParameter("selectedQuantity") != null)
        {
            quantityProd = Integer.parseInt(request.getParameter("selectedQuantity"));
            session.setAttribute("defaultQuantity", quantityProd);  
        }
        else
            quantityProd = 1;
        
        
      
        try
        {
            allCategories = businessLayer.getAllCategories();
            request.setAttribute("listCategories", allCategories);
            
            productsCategory = businessLayer.getProductOfCategory(idCategory);
            request.setAttribute("listeProducts", productsCategory);
            
            
            if(idProduct != null)
            {
                productSelected = businessLayer.getProduct(idProduct);
                
                if(productSelected.getPromotion() != null)
                    calculatePromo(productSelected, request);
                calculatePriceTot(productSelected, quantityProd, request);
                
                if(request.getParameter("addToBasket") != null)
                {
                    basket = (Basket)session.getAttribute("basket");
                    basket.addProducts(productSelected, quantityProd);
                    double priceTot = businessLayer.calculatePriceTot(productSelected, quantityProd);
                    basket.getHashProductsLine().get(String.valueOf(productSelected.getId())).setPriceTot(priceTot);
                    double priceUnit = businessLayer.calculatePriceUnit(productSelected);
                    basket.getHashProductsLine().get(String.valueOf(productSelected.getId())).setPriceUnit(priceUnit);
                }
                    
                request.setAttribute("productSelected", productSelected);
            }
            
            rd = request.getRequestDispatcher("catalog.jsp");
        }
        catch(ConnectionException ce)
        {
            request.setAttribute("connectionError", ce.getError());
            rd = request.getRequestDispatcher("connectionError.jsp");
        }
        finally
        {
            rd.forward(request, response);
        }
        
        
    }
    
    private void calculatePromo(Product productSelected, HttpServletRequest request) 
    {
        GregorianCalendar dateNow = new GregorianCalendar();
            
        if(productSelected.getPromotion().getStartDate().getTimeInMillis() < dateNow.getTimeInMillis() && productSelected.getPromotion().getEndDate().getTimeInMillis() > dateNow.getTimeInMillis())
        {
            if(productSelected.getPromotion().getDiscountPercentage() != null)
            {
                BricoWebUserBusiness businessLayer = new BricoWebUserBusiness();
                double promoPrice = businessLayer.calculatePromo(productSelected);
                DecimalFormat formatPromo = new DecimalFormat("#####.00");
                request.setAttribute("promoPrice", formatPromo.format(promoPrice));
            }
            else
            {
                request.setAttribute("quantityOffered", productSelected.getPromotion().getQuantityOffered());
                request.setAttribute("quantityToPurchase", productSelected.getPromotion().getQuantityToPurchase());
            }     
        }
    }
    private void calculatePriceTot(Product productSelected, int quantiytProd, HttpServletRequest request)
    {
        BricoWebUserBusiness businessLayer = new BricoWebUserBusiness();
        double priceTot = businessLayer.calculatePriceTot(productSelected, quantiytProd);
        
        DecimalFormat formatPriceTot = new DecimalFormat("#####.00");
        request.setAttribute("priceTot", formatPriceTot.format(priceTot));
    }  
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
